<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="规格名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入规格名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品类Id" prop="categoryId">
        <el-input
          v-model="queryParams.categoryId"
          placeholder="请输入品类Id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:rule:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:rule:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:rule:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:rule:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="ruleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="规格名称" align="center" prop="name" />
      <el-table-column label="规格状态" align="center" prop="status" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="品类Id" align="center" prop="categoryId" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:rule:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:rule:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品规格对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ruleRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="规格名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入规格名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <!-- <el-form-item label="品类Id" prop="categoryId">
          <el-input v-model="form.categoryId" placeholder="请输入品类Id" />
        </el-form-item> -->
        <el-divider content-position="center">规格详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddRuleAttrInfo"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="Delete"
              @click="handleDeleteRuleAttrInfo"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="ruleAttrInfoList"
          :row-class-name="rowRuleAttrInfoIndex"
          @selection-change="handleRuleAttrInfoSelectionChange"
          ref="ruleAttrInfo"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            width="50"
          />
          <el-table-column label="类目名称" prop="name" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.name" placeholder="请输入类目名称" />
            </template>
          </el-table-column>

          <!-- 规格属性值tags -->
          <el-table-column label="规格属性值" width="150">
            <template #default="scope">
              <!-- <el-input v-model="scope.row.attrValue" placeholder="请输入规格属性值" /> -->
              <div class="flex gap-2">
                <el-tag
                  v-for="tag in dynamicTags"
                  type="success"
                  :key="tag"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scope.row, tag)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  v-if="inputVisible"
                  ref="InputRef"
                  v-model="inputValue"
                  class="w-20"
                  size="small"
                  @keyup.enter="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                />
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput"
                >
                  + New Tag
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Rule">
import {
  listRule,
  getRule,
  delRule,
  addRule,
  updateRule,
} from "@/api/system/rule";

import { nextTick, ref } from "vue";
import { ElInput } from "element-plus";

const inputValue = ref("");
// 声明标签
const dynamicTags = ref([]);
const inputVisible = ref(false);
const InputRef = ref();

const ruleAttrs = ref(dynamicTags);

function handleClose(tag) {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
}

function showInput() {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value.focus();
  });
}

function handleInputConfirm(ff) {
  //通过角标获取当前索引  获取当前点击对象
  let d = ruleAttrInfoList.value[ff.index - 1];
  d.attrValue = d.attrValue ? d.attrValue : [];
  d.attrValue.push(inputValue.value);

  inputVisible.value = false;
  inputValue.value = "";
}

const { proxy } = getCurrentInstance();

const ruleList = ref([]);
const ruleAttrInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedRuleAttrInfo = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    status: null,
    categoryId: null,
  },
  rules: {
    createBy: [{ required: true, message: "创建人不能为空", trigger: "blur" }],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品规格列表 */
function getList() {
  loading.value = true;
  listRule(queryParams.value).then((response) => {
    ruleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    status: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    categoryId: null,
  };
  ruleAttrInfoList.value = [];
  proxy.resetForm("ruleRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加商品规格";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getRule(_id).then((response) => {
    form.value = response.data;
    ruleAttrInfoList.value = response.data.ruleAttrInfoList;
    open.value = true;
    title.value = "修改商品规格";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ruleRef"].validate((valid) => {
    if (valid) {
      form.value.ruleAttrInfoList = ruleAttrInfoList.value;
      if (form.value.id != null) {
        updateRule(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRule(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除商品规格编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delRule(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 规格详情序号 */
function rowRuleAttrInfoIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 规格详情添加按钮操作 */
function handleAddRuleAttrInfo() {
  let obj = {};
  obj.name = "";
  obj.attrValue = "";
  obj.remark = "";
  ruleAttrInfoList.value.push(obj);
}

/** 规格详情删除按钮操作 */
function handleDeleteRuleAttrInfo() {
  if (checkedRuleAttrInfo.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的规格详情数据");
  } else {
    const ruleAttrInfos = ruleAttrInfoList.value;
    const checkedRuleAttrInfos = checkedRuleAttrInfo.value;
    ruleAttrInfoList.value = ruleAttrInfos.filter(function (item) {
      return checkedRuleAttrInfos.indexOf(item.index) == -1;
    });
  }
}

/** 复选框选中数据 */
function handleRuleAttrInfoSelectionChange(selection) {
  checkedRuleAttrInfo.value = selection.map((item) => item.index);
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/rule/export",
    {
      ...queryParams.value,
    },
    `rule_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
